package com.my.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO channel3
 * @author Lelezhang
 * @create 2020-07-26 23:21
 */
public class NIOFileChannel3 {
    public static void main(String[] args) throws Exception {
        // 创建输入输出输出流
        FileInputStream fileInputStream = new FileInputStream("channel1.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("channel3.txt");
        // 获取channel
        FileChannel fileInputStreamChannel = fileInputStream.getChannel();
        FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();
        // 创建字节缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        // 循环读取
        while (true) {
            // 清空buffer
            byteBuffer.clear();
            int read = fileInputStreamChannel.read(byteBuffer);
            if (read == -1) {
                break;
            }
            // 反转读转写
            byteBuffer.flip();
            fileOutputStreamChannel.write(byteBuffer);
        }
        // 关闭流
        fileInputStreamChannel.close();
        fileOutputStreamChannel.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}
